package com.bugbuff.dubbo.server.interceptor;

import com.bugbuff.common.pojo.User;
import com.bugbuff.common.utils.BanComment;
import com.bugbuff.common.utils.BanPublishing;
import com.bugbuff.common.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class FrozenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验handler是否是HandlerMethod
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        User user = UserThreadLocal.get();
        String frozenUserRedisKey = "FROZEN_USER_" + user.getId();

//        判断该用户是否被冻结登录
        if (redisTemplate.opsForHash().hasKey(frozenUserRedisKey, "1")) {
            response.setCharacterEncoding("UTF-8");
            response.setStatus(403);
            response.getWriter().write("您的账号已经被系统冻结！");
            return false;
        }

//        判断该用户是否被冻结发布评论
        if (redisTemplate.opsForHash().hasKey(frozenUserRedisKey, "2")) {
            //判断是否包含@BanComment注解，如果包含，直接拦截
            if (((HandlerMethod) handler).hasMethodAnnotation(BanComment.class)) {
                response.setCharacterEncoding("UTF-8");
                response.setStatus(403);
                response.getWriter().write("您已被冻结发布评论！");
                return false;
            }
        }

//        判断该用户是否被冻结发布动态
        if (redisTemplate.opsForHash().hasKey(frozenUserRedisKey, "3")) {
            //判断是否包含@BanPublishing注解，如果包含，直接拦截
            if (((HandlerMethod) handler).hasMethodAnnotation(BanPublishing.class)) {
                response.setCharacterEncoding("UTF-8");
                response.setStatus(403);
                response.getWriter().write("您已被冻结发布动态！");
                return false;
            }
        }

        return true;
    }

}
